import {GraphQLNonNull, GraphQLString, GraphQLBoolean, GraphQLID} from "graphql";
import {mutationWithClientMutationId, cursorForObjectInConnection} from "graphql-relay";
import WtpType from "../../types/WtpType";
import { Wtp } from '../../models';
import {connectionFromType} from "../../connection";
import UserType from "../../types/UserType";

const AddWtpMutation = mutationWithClientMutationId({
  name: 'addWtp',
  inputFields: {
    sn: { type: new GraphQLNonNull(GraphQLString) },
    name: { type: new GraphQLNonNull(GraphQLString) },
    mac: { type: new GraphQLNonNull(GraphQLString) },
    position: { type: new GraphQLNonNull(GraphQLString) },
    isMap: { type: GraphQLString },
    status: { type: GraphQLBoolean },
    company_id: { type: GraphQLID },
    contract_id: { type: GraphQLID },
    profile_id: { type: GraphQLID },
  },
  outputFields: {
    wtpEdge: {
      type: connectionFromType('wtp', WtpType).edge,
      resolve: async ({ wtpId }) => {
        const wtps = await Wtp.findAll({});
        const wtp = wtps.find(o => o.get('id') === wtpId);
        return {
          cursor: cursorForObjectInConnection(wtps, wtp),
          node: wtp,
        };
      },
    },
    viewer: {
      type: UserType,
      resolve: async ({ viewer }) => viewer,
    }
  },
  mutateAndGetPayload: async({ sn, name, mac, position, isMap, company_id, contract_id }, { viewer }) => {
    const wtp = await Wtp.create({
      sn,
      name,
      mac,
      position,
      isMap,
      company_id,
      contract_id,
    });
    const wtpId = wtp.dataValues.id;
    return { wtpId, viewer };
  },
});

export default AddWtpMutation;
